package com.zhugang.week04;

/**
 * @program algorithms
 * @description: myPow
 * @author: chanzhugang
 * @create: 2022/06/24 11:24
 */
public class MyPow {

    /**
     * 剑指offer 16 数值的整数次方
     *
     * @param x
     * @param n
     * @return
     */
    public double myPow(double x, int n) {
        if (n >= 0) {
            return rPow(x, n);
        } else {
            // 越界转一下
            return 1 / (rPow(x, -1 * (n + 1)) * x);
        }
    }

    private double rPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        double halfPow = rPow(x, n / 2);
        // (x * x )* (x * x) * x  -> half * half * x
        if (n % 2 == 1) {
            return halfPow * halfPow * x;
        } else {
            return halfPow * halfPow;
        }
    }
}